package HttpClient

import (
	"bytes"
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"io/ioutil"
	"net/http"
	"reflect"
	"strings"
)

func ExecuteRestful(url, method string, header map[string]string, requestJson string) (string, error) {
	method = strings.ToUpper(method)
	if method == "POST" || method == "PUT" {
		return doPostOrPut(url, method, requestJson, header)
	}
	if method == "GET" || method == "DELETE" {
		uri := url
		par := ""
		idx := strings.IndexAny(url, "?")
		if idx >= 0 {
			uri = uri[:idx]
			par = uri[idx+1:]
		}

		return doGetOrDelete(uri, method, par, header)
	}

	return "", errors.New("不支持的操作")

}

func POST(url string, body interface{}, header map[string]string) (string, error) {
	return doPostOrPut(url, "POST", body, header)
}

func PUT(url string, body interface{}, header map[string]string) (string, error) {
	return doPostOrPut(url, "PUT", body, header)
}

func doPostOrPut(url string, method string, body interface{}, header map[string]string) (string, error) {
	// 转换为字符串格式
	jsn := ""
	if reflect.TypeOf(body).Kind() == reflect.String {
		jsn = body.(string)
	} else {
		jsn = Json.BuildJson(body)
	}

	// 发送请求
	request, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsn)))
	if err != nil {
		return "", err
	}

	request.Header.Set("Content-Type", "application/json")

	for key, value := range header {
		request.Header.Set(key, value)
	}

	// 发送请求
	respond, err := http.DefaultClient.Do(request)
	if err != nil {
		return "", err
	}
	defer respond.Body.Close()

	data, err := ioutil.ReadAll(respond.Body)
	if err != nil {
		return "", err
	}

	return string(data), nil
}

func GET(url string, queryParams string, header map[string]string) (string, error) {
	return doGetOrDelete(url, "GET", queryParams, header)
}

func DELETE(url string, queryParams string, header map[string]string) (string, error) {
	return doGetOrDelete(url, "DELETE", queryParams, header)
}

func doGetOrDelete(url string, method string, queryParams string, header map[string]string) (string, error) {
	// 检查URL是否已经包含查询字符串
	if queryParams != "" {
		if strings.Index(url, "?") == -1 {
			url += "?" + queryParams
		} else {
			url += "&" + queryParams
		}
	}

	// 发送请求
	request, err := http.NewRequest(method, url, nil)
	if err != nil {
		return "", err
	}

	for key, value := range header {
		request.Header.Set(key, value)
	}

	// 发送请求
	respond, err := http.DefaultClient.Do(request)
	if err != nil {
		return "", err
	}
	defer respond.Body.Close()

	data, err := ioutil.ReadAll(respond.Body)
	if err != nil {
		return "", err
	}

	return string(data), nil
}
